program ServerConsole;
{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Winapi.Windows,
  Winapi.ShellAPI,
  IdHTTPWebBrokerBridge,
  Web.WebReq,
  Web.WebBroker,
  WebModuleUnit1 in 'WebModuleUnit1.pas' {WebModule1: TWebModule},
  ScuolaMaternaAppControllerU in 'ScuolaMaternaAppControllerU.pas',
  BusinessObjectsU in '..\..\commons\BusinessObjectsU.pas',
  AttributesU in '..\..\commons\AttributesU.pas',
  ConnectionU in '..\..\ServerCommons\ConnectionU.pas',
  FirebirdConnectionU in '..\..\ServerCommons\FirebirdConnectionU.pas',
  InterfaceConnectionU in '..\..\ServerCommons\InterfaceConnectionU.pas',
  InterfaceU in '..\..\ServerCommons\InterfaceU.pas',
  PersistencyConnectionU in '..\..\ServerCommons\PersistencyConnectionU.pas',
  ServiceFbU in '..\..\ServerCommons\ServiceFbU.pas';

{$R *.res}

procedure RunServer(APort: Integer);
var
  LInputRecord: TInputRecord;
  LEvent: DWord;
  LHandle: THandle;
  LServer: TIdHTTPWebBrokerBridge;
begin
  Writeln(Format('Starting HTTP Server or port %d', [APort]));
  LServer := TIdHTTPWebBrokerBridge.Create(nil);
  try
    LServer.DefaultPort := APort;
    LServer.Active := True;
    ShellExecute(0, 'open', pChar('http://localhost:' + inttostr(APort) +
      '/getalunni/2012-2013'), nil, nil,
      SW_SHOWMAXIMIZED);
    Writeln('Press ESC to stop the server');
    LHandle := GetStdHandle(STD_INPUT_HANDLE);
    while True do
    begin
      Win32Check(ReadConsoleInput(LHandle, LInputRecord, 1, LEvent));
      if (LInputRecord.EventType = KEY_EVENT) and
      LInputRecord.Event.KeyEvent.bKeyDown and
      (LInputRecord.Event.KeyEvent.wVirtualKeyCode = VK_ESCAPE) then
        break;
    end;
  finally
    LServer.Free;
  end;
end;

begin
  try
  if WebRequestHandler <> nil then
    WebRequestHandler.WebModuleClass := WebModuleClass;
    WebRequestHandlerProc.MaxConnections := 1024;
    RunServer(3000);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end
end.
